package th.retrofit.lib;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * https://leetcode-cn.com/problems/longest-consecutive-sequence/
 * 给定一个未排序的整数数组 nums ，找出数字连续的最长序列（不要求序列元素在原数组中连续）的长度。
 *
 * 请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
 *
 */
public class Solution128 {

    public int longestConsecutive(int[] nums) {
        int nLen = nums.length;
        if (nLen == 0) return 0;
        int max = 0;
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < nLen; i++) {
            set.add(nums[i]);
        }
        for (int i : set) {
            if (!set.contains(i - 1)) {
                int curLen = 1;
                while (set.contains(i + 1)) {
                    i++;
                    curLen++;
                }
                max = Math.max(max, curLen);
            }
        }
        return max;
    }

    public int longestConsecutive1(int[] nums) {
        Arrays.sort(nums);
        int count = 1;
        int max = 1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == nums[i - 1] + 1) {
                count++;
            } else {
                max = Math.max(max, count);
                count = 1;
            }
        }
        max = Math.max(max, count);
        return max;
    }

    public static void main(String[] args) {
        int[] arr = new int[]{0,3,7,2,5,8,4,6,0,1};
        System.out.println(new Solution128().longestConsecutive(arr));
    }

}
